<template>
  <div class="container" v-loading="status_loading">
    <el-row>
      <el-col :span="24">
        <h2 class="title">{{title}}</h2>
        <el-form ref="refForm" :model="formData" :rules="formRule">
          <div>
            <el-table
              ref="table"
              stripe
              empty-text
              fits
              class="single-select-table"
              :data="formData.detailList"
              :row-style="tableRowStyle"
              :row-class-name="tableRowClassName"
              @row-click="rowClick"
              @selection-change="handleSingleSelectionChange"
            >
              <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
              <el-table-column label="TakeOff Location" align="center">
                <template slot-scope="scope">
                  <el-form-item size="mini" :prop="'detailList.'+scope.$index+'.sourcelocationcode'" :rules="formRule.sourcelocationcode">
                    <!-- {{'tableData.'+scope.$index+'.unedit'}} -->
                    <el-input readonly @focus="showLocation($event,scope.row)" v-model="scope.row.sourcelocationcode" :disabled="formData.detailList[scope.$index].unedit"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="SKU">
                <template slot-scope="scope">
                  <el-form-item size="mini" :prop="'detailList.'+scope.$index+'.productspeccode'" :rules="formRule.productspeccode">
                    <el-select @change="getProductInfo(scope.row)" v-model="scope.row.productspeccode" :disabled="formData.detailList[scope.$index].unedit">
                      <el-option v-for="(item,index) in scope.row.skuList" :key="index" :label="item.productspeccode" :value="item.productspeccode"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="ProductName" align="center">
                <template slot-scope="scope">
                  <span>{{formData.detailList[scope.$index].productname}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="Specification">
                <template slot-scope="scope">
                  <span>{{formData.detailList[scope.$index].productspec}}</span>
                </template>
              </el-table-column>
              <el-table-column label="BatchNum" align="center">
                <template slot-scope="scope">
                  <el-form-item size="mini" :prop="'detailList.'+scope.$index+'.batchnum'" :rules="formRule.batchnum">
                    <el-select v-model="formData.detailList[scope.$index].batchnum" placeholder :disabled="formData.detailList[scope.$index].isdisabled">
                      <el-option v-for="item in batch" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="Shift Qty">
                <template slot-scope="scope">
                  <el-form-item size="mini" :prop="'detailList.'+scope.$index+'.quantity'" :rules="formRule.quantity">
                    <el-input @input="validateNumber('quantity',scope.$index)" maxlength="5" show-word-limit v-model="scope.row.quantity" :disabled="formData.detailList[scope.$index].isdisabled"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="PutAway Location">
                <template slot-scope="scope">
                  <el-form-item size="mini" :prop="'detailList.'+scope.$index+'.targetlocationcode'" :rules="formRule.targetlocationcode">
                    <el-input readonly @focus="showLocation2($event,scope.row)" v-model="scope.row.targetlocationcode" :disabled="formData.detailList[scope.$index].isdisabled"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column width="180px" align="center" :label="$t('m.operation')">
                <template slot-scope="scope">
                  <!-- <div v-if="scope.row.editbtn" style="display:inline-block;margin-right:10px"> -->
                  <el-button v-if="scope.row.edit" size="mini" @click.native.prevent="editRow(scope.$index, scope.row)" type="primary">{{$t('m.edit')}}</el-button>
                  <el-button v-if="scope.row.cancel" size="mini" @click.native.prevent="cancelRow(scope.$index,scope.row)">{{$t('m.cancel')}}</el-button>

                  <el-button v-if="scope.row.save" size="mini" @click.native.prevent="saveRow(scope.$index, scope.row)" type="primary">{{$t('m.save')}}</el-button>
                  <el-button v-if="scope.row.delete" size="mini" @click.native.prevent="deleteRow(scope.$index, formData.detailList,scope.row)" type="danger">{{$t('m.delete')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div align="left">
              <el-button type="primary" @click.stop="addRow">{{$t('m.add')}}Source Location</el-button>
            </div>
          </div>
        </el-form>

        <div class="btns">
          <el-button v-if="option=='add'" type="primary" @click.stop="save('refForm')">{{$t('m.confirm')}}</el-button>
          <el-button type="primary" @click="back">{{$t('m.back')}}</el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 选择库位dialog start -->
    <locationListPopup v-if="locationListPopupVisible" :popupVisible="locationListPopupVisible" :config="locationConfig" @submit="setLocation" @close="locationListPopupVisible=false"></locationListPopup>
    <!-- 选择库位dialog end -->
  </div>
</template>

<script>
export default {
  data(){
    let onlyNumber = (rule, value, callback) => {
      if (!/^\+?[1-9]\d*$/.test(value) && value){
        return callback(new Error(this.$t('m.onlynumber')))
      }
      callback()
    }
    return {
      locationListPopupVisible:false,
      locationConfig:{}, // 需要传递给locations-list组件的参数
      status_loading:false,
      batch:[],
      formData:{
        detailList:[
          {
            batchnum:'none',
            productid:null,
            productname:'',
            productspec:'',
            productspeccode:'',
            quantity:null,
            sourcelocationcode:'',
            sourcelocationid:null,
            soureareaid:null,
            state:1,
            suppliercode:'',
            targetareaid:null,
            targetlocationcode:'',
            targetlocationid:null,
            unedit:false,
            isdisabled:false,
            edit:false, //控制显示编辑/保存按钮
            cancel:false,
            editbtn:false, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
            delete:true,
            save:false
          }
        ],
        state:1,
        timelimit:0
      },
      formRule:{
        batchnum:[
          {
            required:true,
            message:this.$t('m.choose') + 'SKU',
            trigger:'change'
          }
        ],
        productspeccode:[
          {
            required:true,
            message:this.$t('m.choose') + 'SKU',
            trigger:'change'
          }
        ],
        quantity:[
          {
            required:true,
            message:this.$t('m.enter') + 'Shift Qty',
            trigger:'blur'
          },
          { validator:onlyNumber, trigger:'blur' }
        ],
        sourcelocationcode:[
          {
            required:true,
            message:this.$t('m.enter') + 'TakeOff Location',
            trigger:'change'
          }
        ],
        targetlocationcode:[
          {
            required:true,
            message:this.$t('m.enter') + 'PutAway Location',
            trigger:'change'
          }
        ]
      },
      dialogFormVisible:false,
      formLabelWidth:'140px',
      option:'',
      title:'',
      warehouseList:[],
      partitionList:[],
      regionList:[],
      locationList:[],
      id:null,
      visibleAll:false,
      formLabelAlign:{
        identificationcode:'',
        partitioncode:'',
        channel:'',
        grating:'',
        level:'',
        shelves:''
      },
      locationcode:'',
      target:{}, //保存当前点击了哪一个input
      row:{},
      areashiftid:null
    }
  },
  components:{
    locationListPopup:() => import('@/components/common/location-list')
  },
  props:['obj'],
  watch:{},
  filters:{
    // 1 待处理 2 待拣货 3 拣货中 4 已完成 5 已取消
    stateFilter(value, lan){
      return [
        lan('m.quality.state1'),
        lan('m.out.state2'),
        lan('m.out.state3'),
        lan('m.shelves.state5'),
        lan('m.shelves.state3')
      ][value - 1]
    }
  },
  computed:{},
  methods:{
    validateNumber(key,index){
      this.$set(this.formData.detailList[index],key,this.formData.detailList[index][key].toString().replace(/[^\d]/g,''))
    },
    back(){
      let obj = {
        componentName:'areashift'
      }
      this.$emit('switchComponent', obj)
      this.resetData()
    },
    //获取所有库位
    // getLocation() {
    //   this.$axios({
    //     method: "get",
    //     url: `/locationinfo/list`,
    //     params: {
    //       warehouseid: this.$store.state.basicInfo.warehouseInfo.id,
    //       identificationcode: this.formLabelAlign.identificationcode.toUpperCase(),
    //       partitioncode: this.formLabelAlign.partitioncode,
    //       channel: this.formLabelAlign.channel,
    //       shelves: this.formLabelAlign.shelves,
    //       level: this.formLabelAlign.level,
    //       grating: this.formLabelAlign.grating
    //     }
    //   }).then(({data})=> {
    //     this.locationList = data;
    //   });
    // },
    clearData(){
      if (
        this.formData.partitionid &&
        this.formData.areaid &&
        this.formData.detailList[0].sourcelocationcode
      ){
        this.$confirm(
          this.$t('m.transposing.clear'),
          this.$t('m.noticemessage'),
          {
            confirmButtonText:this.$t('m.confirm'),
            cancelButtonText:this.$t('m.cancel'),
            center:true
          }
        ).then(() => {
          this.formData.detailList = [
            {
              batchnum:'none',
              productid:null,
              productname:'',
              productspec:'',
              productspeccode:'',
              quantity:null,
              sourcelocationcode:'',
              sourcelocationid:null,
              soureareaid:null,
              state:1,
              suppliercode:'',
              targetareaid:null,
              targetlocationcode:'',
              targetlocationid:null,
              unedit:false,
              isdisabled:false,
              edit:false, //控制显示编辑/保存按钮
              cancel:false,
              editbtn:false, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
              delete:true,
              save:false
            }
          ]
        })
      } else {
        this.formData.detailList = [
          {
            batchnum:'none',
            productid:null,
            productname:'',
            productspec:'',
            productspeccode:'',
            quantity:null,
            sourcelocationcode:'',
            sourcelocationid:null,
            soureareaid:null,
            state:1,
            suppliercode:'',
            targetareaid:null,
            targetlocationcode:'',
            targetlocationid:null,
            unedit:false,
            isdisabled:false,
            edit:false, //控制显示编辑/保存按钮
            editbtn:false, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
            delete:true,
            save:false,
            cancel:false
          }
        ]
      }
    },
    resetLocation(){
      this.visibleAll = false
      this.formLabelAlign = {
        identificationcode:'',
        partitioncode:'',
        channel:'',
        grating:'',
        level:'',
        shelves:''
      }
      // this.getLocation();
    },
    getSku(locationcode){
      this.$axios({
        method:'get',
        url:'/locationstock/getlsinfosbylc',
        params:{
          locationcode:locationcode
        }
      }).then(({ data }) => {
        this.row.skuList = data
        if (this.row.skuList.length === 1){
          this.row.productspeccode = this.row.skuList[0].productspeccode
          this.getProductInfo(this.row)
        }
      })
    },
    getProductInfo(row){
      this.$axios({
        method:'get',
        url:'/locationshift/getlsinfoforls',
        params:{
          locationcode:row.sourcelocationcode,
          productspeccode:row.productspeccode
        }
      }).then(({ data, code }) => {
        if (code === 0){
          row.productname = data.productname
          row.productspec = data.productspec
          row.productid = data.productid
          row.sourcelocationid = data.locationid
          row.quantity=data.productstocksum
        } else {
          row.productname = ''
          row.productspec = ''
          row.productid = null
          row.sourcelocationid = null
        }
      }).catch(() => {
        row.skuList = []
        row.productspeccode = ''
        row.sourcelocationcode = ''
        row.targetlocationcode = ''
        row.quantity = null
      })
    },
    showLocation(event, row){
      this.locationConfig = {
        url:'/locationinfo/listwithnost'
      }
      this.locationListPopupVisible = true
      this.target = event.target
      this.row = row
      this.code = 'source'
    },
    showLocation2(event, row){
      this.locationConfig = {
        url:'locationinfo/listwithnousage'
      }
      this.locationListPopupVisible = true
      this.target = event.target
      this.row = row
      this.code = 'target'
    },
    setLocation(location){
      this.locationListPopupVisible = false
      this.locationcode = location.locationcode
      if (this.code === 'source'){
        this.row.productspeccode = ''
        this.row.productname = ''
        this.row.productspec = ''
        this.getSku(this.locationcode)
        this.row.sourcelocationcode = location.locationcode
        this.row.sourcelocationid = location.locationid
        this.row.soureareaid = location.areaid
        //this.formData.detailList.splice(index, 1, this.row);
      }
      if (this.code === 'target'){
        this.row.targetlocationcode = location.locationcode
        this.row.targetlocationid = location.locationid
        this.row.targetareaid = location.areaid
        // this.$axios({
        //   method:'get',
        //   url:`/locationstock/checklocation`,
        //   params:{
        //     locationcode:location.locationcode
        //   }
        // }).then(() => {
        //   this.row.targetlocationcode = location.locationcode
        //   this.row.targetlocationid = location.locationid
        //   this.row.targetareaid = location.areaid
        // }).catch(() => {
        //   this.row.targetlocationcode = ''
        //   this.row.targetlocationid = null
        //   this.row.targetareaid = null
        // })
      }
    },
    save(formName){
      this.$refs[formName].validate(valid => {
        if (valid){
          this.$axios({
            method:'post',
            url:'/areashift/add',
            data:this.formData
          }).then(() => {
            this.$message({
              type:'success',
              message:this.$t('m.success')
            })
            this.back()
          })
        }
      })
    },
    editRow(index, row){
      row.isdisabled = false
      row.edit = false
      row.cancel = true
      row.save = true
      row.delete = false
    },
    cancelRow(index, row){
      this.$axios({
        method:'get',
        url:`/areashiftdetail/${row.detailid}`,
        data:row
      }).then(({ data }) => {
        data.isdisabled = true
        data.edit = true
        data.cancel = false
        data.save = false
        data.delete = true
        data.unedit = true
        this.formData.detailList.splice(index, 1, data)
      })
    },
    saveRow(index, row){
      this.$refs.refForm.validate(valid => {
        if (valid){
          //有detailid就是编辑保存
          if (row.detailid){
            this.$axios({
              method:'put',
              url:`/areashiftdetail/${row.detailid}`,
              data:row
            }).then(() => {
              row.unedit = true
              row.isdisabled = true
              row.edit = true
              row.save = false
              row.cancel = false
              row.delete = true
              this.formData.detailList.splice(index, 1, row)
              this.$message({
                type:'success',
                message:this.$t('m.editSuccess')
              })
            })
          } else {
            row.areashiftid = this.areashiftid
            this.$axios({
              method:'post',
              url:`/areashiftdetail/add`,
              data:row
            }).then(({ data }) => {
              row.detailid = data.detailid
              row.unedit = true
              row.isdisabled = true
              row.edit = true
              row.save = false
              row.cancel = false
              row.delete = true
              this.formData.detailList.splice(index, 1, row)
              this.$message({
                type:'success',
                message:this.$t('m.success')
              })
            })
          }
        }
      })
    },
    deleteRow(index, rows, row){
      if (row.detailid){
        if (rows.length <= 1){
          this.$confirm(
            this.$t('m.areashift.deleteAlert'),
            this.$t('m.delete'),
            {
              confirmButtonText:this.$t('m.confirm'),
              cancelButtonText:this.$t('m.cancel'),
              center:true
            }
          ).then(() => {
            this.$axios({
              method:'delete',
              url:`/areashiftdetail/${row.detailid}`
            }).then(() => {
              this.$message({
                type:'success',
                message:this.$t('m.deleteSuccess')
              })
              this.back()
            })
          })
        } else {
          this.$confirm(this.$t('m.deleteAlert'), this.$t('m.delete'), {
            confirmButtonText:this.$t('m.confirm'),
            cancelButtonText:this.$t('m.cancel'),
            center:true
          }).then(() => {
            this.$axios({
              method:'delete',
              url:`/areashiftdetail/${row.detailid}`
            }).then(() => {
              this.$message({
                type:'success',
                message:this.$t('m.deleteSuccess')
              })
              this.getInfo()
            })
          })
        }
      } else {
        rows.splice(index, 1)
      }
    },
    addRow(){
      if (this.option === 'edit'){
        this.formData.detailList.push({
          skuList:[],
          batchnum:'none',
          productid:null,
          productname:'',
          productspec:'',
          productspeccode:'',
          quantity:null,
          sourcelocationcode:'',
          sourcelocationid:null,
          soureareaid:null,
          state:1,
          suppliercode:'',
          targetareaid:null,
          targetlocationcode:'',
          targetlocationid:null,
          unedit:false,
          isdisabled:false,
          edit:false, //控制显示编辑/保存按钮
          cancel:false,
          editbtn:false, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
          delete:true,
          save:true
        })
      } else {
        this.formData.detailList.push({
          batchnum:'none',
          productid:null,
          productname:'',
          productspec:'',
          productspeccode:'',
          quantity:null,
          sourcelocationcode:'',
          sourcelocationid:null,
          soureareaid:null,
          state:1,
          suppliercode:'',
          targetareaid:null,
          targetlocationcode:'',
          targetlocationid:null,
          unedit:false,
          isdisabled:false,
          edit:false, //控制显示编辑/保存按钮
          cancel:false,
          editbtn:false, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
          delete:true,
          save:false
        })
      }
    },
    resetData(){
      this.isdisabled = false
      this.partitionList = []
      this.regionList = []
      this.locationList = []
      this.formData = {
        detailList:[
          {
            batchnum:'none',
            productid:null,
            productname:'',
            productspec:'',
            productspeccode:'',
            quantity:null,
            sourcelocationcode:'',
            sourcelocationid:null,
            soureareaid:null,
            state:1,
            suppliercode:'',
            targetareaid:null,
            targetlocationcode:'',
            targetlocationid:null,
            unedit:false,
            isdisabled:false,
            edit:false, //控制显示编辑/保存按钮
            cancel:false,
            editbtn:false, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
            delete:true,
            save:false
          }
        ],
        state:1,
        timelimit:0
      }
    },
    getInfo(){
      this.$axios({
        method:'get',
        url:`/areashift/${this.id}`
      }).then(({ data }) => {
        this.formData = data
        this.areashiftid = data.areashiftid
        this.formData.detailList.forEach(element => {
          let obj = {
            unedit:true,
            isdisabled:true,
            edit:true, //控制显示编辑/保存按钮
            cancel:false,
            editbtn:true, //判断需不需要显示编辑按钮，如果是新添加的就不需要编辑
            delete:true,
            save:false
          }
          Object.assign(element, obj)
        })

        this.status_loading = false
      })
    }
  },
  activated(){
    this.option = this.obj.option
    this.id = this.obj.id
    // this.$nextTick(() => {

    // })
    this.$refs.refForm.clearValidate()
    if (this.option === 'add'){
      this.title = this.$t('m.add') + this.$t('m.areashift.name')
    }
    if (this.option === 'edit'){
      this.status_loading = true
      this.title = this.$t('m.edit') + this.$t('m.areashift.name')
      this.getInfo()
    }
    if (!this.option){
      this.back()
    }
  }
}
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.title {
  margin-bottom: 30px;
}
table .el-form-item--mini.el-form-item,
table .el-form-item--small.el-form-item {
  margin-bottom: 0;
}
::v-deep.el-radio {
  width: 130px;
  margin-bottom: 5px;
}
::v-deep.abow_dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
  .el-dialog {
    margin: 0 auto !important;
    height: 90%;
    overflow: hidden;
    .el-dialog__body {
      height: 80%;
      position: absolute;
      left: 0;
      top: 54px;
      bottom: 0;
      right: 0;
      padding: 0;
      z-index: 1;
      overflow: hidden;
      overflow-y: auto;
    }
  }
}
::v-deep.abow_dialog {
  .left {
    position: fixed;
    width: 250px;
    top: 10%;
  }
}
::v-deep.abow_dialog {
  .right {
    width: 870px;
    position: absolute;
    right: 0;
    padding-bottom: 30px;
    .btns {
      position: fixed;
      bottom: 10%;
      left: 50%;
    }
  }
}
::v-deep.upper .el-input__inner {
  text-transform: uppercase !important;
}
</style>